import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class udpEchoClient {
    DatagramSocket socket = null;
    private  String serverIP;
    private int serverPort;
    public udpEchoClient(String serverIP,int serverPort) throws SocketException {

        socket = new DatagramSocket();
        this.serverIP = serverIP;
        this.serverPort = serverPort;
    }

    public void start() throws IOException {
        System.out.println("启动客户端");
        Scanner scanner = new Scanner(System.in);

        while (true){
            //1.从控制台读取到用户输入
            //2构造出一个udp请求,发送给服务器
            //3从服务器读取到响应
            //4把响应打印到控制台
            System.out.println("->");
            String request = scanner.next();
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length,
                    InetAddress.getByName(this.serverIP), this.serverPort);
            socket.send(requestPacket);

            DatagramPacket responsePacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);


            String response = new String(responsePacket.getData(),0,responsePacket.getLength());
            System.out.printf(response);
        }
    }

    public static void main(String[] args) throws IOException {
        udpEchoClient client = new udpEchoClient("192.168.0.108",9090);

        client.start();



    }






}
